from sklearn.datasets import fetch_lfw_people
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt

lfw = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
X = lfw.data

n_samples, h, w = lfw.images.shape
n_features = X.shape[1]
print("#Features: "+ str(n_features))

def plot_gallery(images, height, width, n_row, n_col, cmap=plt.cm.gray):
    fig, axs = plt.subplots(n_row,n_col, figsize=(14,10),
                            subplot_kw={'xticks':(), 'yticks':()})
    for i, image in zip(range(n_row*n_col), images):
        r = int(i/n_col); c = i%n_col
        axs[r,c].imshow(image.reshape((h, w)), cmap=cmap) 
        if (r == 0): 
            if(c == 0):
                axs[r,c].set_title('compressed:')  
            else:
                axs[r,c].set_title('{:.2f}'.format(
                                   100-(5+(c-1)*20)*100/n_features) + '%')

n_components = 300

images = []
for face in [100,150,300,400]:  # some faces from the dataset samples
    images.append(X[face])  # draw the original image
    for compressed in range(5,126,20):
        estimator = PCA(n_components=compressed, svd_solver='randomized')
        W = estimator.fit_transform(X)
        # draws the compressed image
        images.append(estimator.inverse_transform(W[face]))  

plot_gallery(images, h, w, 4, 8)
plt.show()
